<template>
  <a-modal
    v-model:visible="dataWrapper.visiable"
    @ok="handleOk"
    @cancel="cancel"
  >
    <template #title>
      <a-space align="center">
        <span>{{ dataWrapper.title }}</span>
        <a-button
          type="primary"
          shape="circle"
          ghost
          size="small"
          @click="emits('randomClient')"
        >
          <template #icon>
            <UndoOutlined />
          </template>
        </a-button>
      </a-space>
    </template>
    <a-form
      :model="dataWrapper.formData"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item has-feedback label="接入方名称" v-bind="validateInfos.name">
        <a-input
          v-model:value="dataWrapper.formData.name"
          placeholder="请输入接入方名称"
        />
      </a-form-item>
      <a-form-item
        has-feedback
        label="Client ID"
        v-bind="validateInfos.clientId"
      >
        <a-input
          v-model:value="dataWrapper.formData.clientId"
          placeholder="请输入Client ID"
        />
      </a-form-item>
      <a-form-item
        has-feedback
        label="Client Secret"
        v-bind="validateInfos.clientSecret"
      >
        <a-input
          v-model:value="dataWrapper.formData.clientSecret"
          placeholder="请输入Client Secret"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { Form } from 'ant-design-vue'
import { ref } from 'vue'
import type { ValidationRule } from 'ant-design-vue/lib/form/Form'
import type { OptionClientDialogForm, OptionClientDialogState } from '../types'
const { useForm } = Form

const props = defineProps<{
  dataWrapper: OptionClientDialogState
}>()

const emits = defineEmits<{
  (e: 'enter'): void
  (e: 'randomClient'): void
}>()

const rules = ref<Record<keyof OptionClientDialogForm, ValidationRule[]>>({
  name: [{ required: true, message: '接入方名称必填' }],
  clientId: [{ required: true, message: 'Client ID必填' }],
  clientSecret: [{ required: true, message: 'Client Secret必填' }],
})

const { validate, validateInfos, resetFields } = useForm(
  props.dataWrapper.formData,
  rules
)

const handleOk = () => {
  validate()
    .then(() => {
      emits('enter')
    })
    .catch((err) => {
      console.error(err.errorFields[0].errors[0])
    })
}

const cancel = () => {
  resetFields()
}
</script>

<style lang="scss" scoped>
@include b(option-client-dialog) {
}
</style>
